/**
 *Express.js数据持久化
 */
// 导入Express模块
const express = require("express");

// 创建express应用
const app = express();

// Express http服务端口
const port = 3001;
//导入MySQL数据库访问模型
const db = require("./db/11_test_db");

//获取指定id的书籍信息
app.get("/:id", function (req, res, next) {
  let bookId = parseInt(req.params.id);
  if (Number.isNaN(bookId)) {
    next();
  } else {
    db.query("SELECT * FROM books WHERE id=?", [bookId])
      .then((result) => {
        console.log(result);
        res.json(result);
      })
      .catch((error) => {
        console.error(error);
        res.end();
      });
  }
});

//获取书籍列表
app.get("/", function (req, res, next) {
  db.query("SELECT * FROM books")
    .then((result) => {
      console.log(result);
      res.json(result);
    })
    .catch((error) => {
      console.error(error);
      res.end();
    });
});

//新增书籍列表
app.post("/", function (req, res, next) {
    let title = "测试书籍信息" + new Date().toLocaleString();
    db.query("INSERT INTO books (title,description) VALUES (?,?)",[
        title,
        "作者：赵六"
    ])
      .then((result) => {
        console.log(result.insertId);
        res.json(result);
      })
      .catch((error) => {
        console.error(error);
        res.end();
      });
  });

  //修改书籍列表
app.put("/:id", function (req, res, next) {
    let bookId = parseInt(req.params.id);
  if (Number.isNaN(bookId)) {
    next();
  } else {
    let title = "测试书籍信息" + new Date().toLocaleString();
    db.query("UPDATE books SET title=?,description=? WHERE id=?", [title,"作者：陈三",bookId])
      .then((result) => {
        console.log(result);
        res.json(result);
      })
      .catch((error) => {
        console.error(error);
        res.end();
      });
  }
  });

  //删除书籍列表
app.delete("/:id", function (req, res, next) {
    let bookId = parseInt(req.params.id);
  if (Number.isNaN(bookId)) {
    next();
  } else {
    db.query("DELETE FROM books WHERE id=?", [bookId])
      .then((result) => {
        console.log(result);
        res.json(result);
      })
      .catch((error) => {
        console.error(error);
        res.end();
      });
  }
  });
// 启动Express服务
app.listen(port, function () {
  console.log(`Myapp访问地址:http://127.0.0.1:${port}`);
});

